// index.js
Page({
  data: {
    imgSrc: "/pages/images/1.jpg",
    imgSrcdetect: "/pages/images/1.jpg",
    recording: false, // 定义录音状态
    tempFilePath: '', // 定义临时文件路径
    result: '' // 定义识别结果
  },
  load() {
    this.setData({ imgSrc: "/pages/images/2.png" });
    console.log("hello");
  },
  startRecord() {
    console.log('Trying to start recording');
    if (this.data.recording) {
      wx.showToast({ title: '正在录音中...', icon: 'none' });
      return;
    }
    this.setData({ recording: true }); // 直接在这里设置录音状态
    const recorderManager = wx.getRecorderManager();
    recorderManager.onStart(() => {
      console.log('recorder onStart');
    });
    recorderManager.onStop((res) => {
      console.log('recorder onStop', res);
      const { tempFilePath } = res;
      this.setData({ recording: false, tempFilePath: tempFilePath });
    });
    recorderManager.start({
      duration: 60000,
      sampleRate: 8000,
      numberOfChannels: 2,
      encodeBitRate: 48000,
      format: 'wav',
      success: () => {
        wx.showToast({ title: '开始录音', icon: 'success' });
      },
      fail: () => {
        this.setData({ recording: false }); // 确保在录音失败时更新状态
        wx.showToast({ title: '录音失败，请检查权限', icon: 'none' });
      }
    });
  },
  stopRecord() {
    console.log('Trying to stop recording');
    if (!this.data.recording) {
      console.log('Recording was not started');
      wx.showToast({
        title: '当前未在录音',
        icon: 'none'
      });
      return;
    }
    this.setData({ recording: false }, () => {
      wx.showToast({
        title: '停止录音',
        icon: 'none'
      });
      console.log('recording status set to false');
    });
    const recorderManager = wx.getRecorderManager();
    recorderManager.stop();
    console.log('stop method called on recorderManager');
  },
  uploadAudio() {
    const that = this;
    if (!this.data.tempFilePath) {
      wx.showToast({ title: '没有录音文件', icon: 'none' });
      return;
    }
    wx.showLoading({ title: '上传中...', });
    wx.uploadFile({
      url: 'http://192.168.1.2:5000/upload', // 正确的上传地址
      filePath: that.data.tempFilePath,
      name: 'file',
      header: { 'content-type': 'multipart/form-data' },
      formData: {
        'user': 'test'
      },
      success: res => {
        wx.hideLoading();
        const data = JSON.parse(res.data);
        if (data.status === 'success') {
          that.setData({ result: data.result });
          wx.showToast({ title: '上传成功', icon: 'success' });
        } else {
          wx.showToast({ title: data.error || '上传失败', icon: 'none' });
        }
      },
      fail: err => {
        wx.hideLoading();
        wx.showToast({ title: '上传失败', icon: 'none' });
        console.error('uploadAudio fail', err);
      }
    });
  }
  
});
